/**
 * Created by fanyuting on 2017/3/18 0018.
 */
//项目根路径
var rootPath = getRootPath();
function accessoryOpenFile(packageKey,uploadUserId){
    var element = $("<input id=\""+packageKey+"\" type=\"file\" name=\"files\" packageKey=\""+packageKey+"\" style='display:none'  multiple />");
    $("body").append(element);
    //上传
    $("#"+packageKey+"").fileupload({
        dataType: 'json',
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        add: function (e, data) {
           // console.log(data.originalFiles[0]);
            var size = data.originalFiles[0].size;
            var fileName =data.originalFiles[0].name;
            var fileText =fileName.substring((fileName.lastIndexOf(".")+1),fileName.length);
            var fileType =fileText.toLowerCase();
            //alert(fileType);
            var arrStr = $("#"+packageKey+"accessoryType").val();
            var maxSize = $("#"+packageKey+"maxSize").val();
            //限制上传文件类型
            //alert(arrStr);
            if(!verifyFileType(arrStr,fileType)){
                alert("该类型文件不允许上传！");
                return ;
            }
            //限制上传大小
            if(size<=0){
                alert("该文件没有内容！");
            }
            if(size>(maxSize*1024*1024)){
                alert("该文件太大！");
                return ;
            }

            //alert(acceptFileTypes.test(data.originalFiles[0]['type'])+",,,,"+data.originalFiles[0]['type']);
            data.url =rootPath+'/accessory/upload.shtml?packageKey='+ packageKey+"&uploadUserId="+uploadUserId;
            data.submit();
        },
        done: function (e, data) {
            var accessoryId = data.result;
            var files = data.originalFiles;
            for(var i=0;i<files.length;i++){
                var d = files[i].lastModifiedDate;
                var time = getNowFormatDate();
                $("#"+packageKey+"accessoryTable").append("<tr id=\""+accessoryId+"_tr\" >" +
                    "<input id='"+accessoryId+"' type='hidden' name='add_accessoryIds' value='"+accessoryId+"'/>"+
                    "<td>"+files[i].name+"</td>" +
                    "<td>"+(files[i].size/1024).toFixed(2)+"KB</td>" +
                    "<td>"+time+"</td>" +
                    "<td>" +
                    "<a class='accessory_deleteBtn' href='javascript:void(0);' onclick=\"accessoryDeleteAccessory('" + accessoryId + "','"+packageKey+"');\" >删除</a>" +
                    "<a class='accessory_downloadBtn' href='javascrip:void(0);' onclick=\"accessoryDownloadAccessory('" + accessoryId + "');\" >下载</a>"+
                    "</td>" +
                    "</tr>");
            }
        },
        /**
         *进度条
         */
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress .bar').css(
                'width',
                progress + '%'
            );
            $('#progress .bar').html(progress+"%");
        },
        //失败
        fail:function(e,data){
            alert("上传失败！");
        }
    });
    $("#"+packageKey+"").click();
}


/**
 * 简单附件标签的上传方法
 * @param packageKey
 * @param uploadUserId
 */
function accessorySimpleOpenFile(packageKey,uploadUserId){
    var element = $("<input id=\""+packageKey+"\" type=\"file\" name=\"files\" packageKey=\""+packageKey+"\" style='display:none'  multiple />");
    $("body").append(element);
    //上传
    $("#"+packageKey+"").fileupload({
        dataType: 'json',
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        add: function (e, data) {
            //console.log(data.originalFiles[0]);
            var size = data.originalFiles[0].size;
            var fileName =data.originalFiles[0].name;
            var fileText =fileName.substring((fileName.lastIndexOf(".")+1),fileName.length);
            var fileType =fileText.toLowerCase();
            //alert(fileType);
            var arrStr = $("#"+packageKey+"accessoryType").val();
            var maxSize = $("#"+packageKey+"maxSize").val();//上传文件限制大小,单位MB
            //限制上传文件类型
            //alert(arrStr);
            if(!verifyFileType(arrStr,fileType)){
                alert("该类型文件不允许上传！");
                return ;
            }
            //alert(size);
            //限制上传大小
            if(size<=0){
                alert("该文件没有内容！");
                return ;
            }
            if(size>(maxSize*1024*1024)){
                alert("该文件太大！");
                return ;
            }

            //alert(acceptFileTypes.test(data.originalFiles[0]['type'])+",,,,"+data.originalFiles[0]['type']);
            data.url =rootPath+'/accessory/upload.shtml?packageKey='+ packageKey+"&uploadUserId="+uploadUserId;
            showProgress(packageKey);
            data.submit();
        },
        done: function (e, data) {
            var accessoryId = data.result;
            var files = data.originalFiles;
            for(var i=0;i<files.length;i++){
                var d = files[i].lastModifiedDate;
                var time = getNowFormatDate();
                hideProgress(packageKey);
                $("#"+packageKey+"accessoryTable").append(/*"<tr id=\""+accessoryId+"_tr\" >" +
                    "<input id='"+accessoryId+"' type='hidden' name='add_accessoryIds' value='"+accessoryId+"'/>"+
                    "<td>"+files[i].name+"</td>" +
                    "<td>"+(files[i].size/1024).toFixed(2)+"KB</td>" +
                    "<td>"+time+"</td>" +
                    "<td>" +
                    "<a class='accessory_deleteBtn' href='javascript:void(0);' onclick=\"accessoryDeleteAccessory('" + accessoryId + "','"+packageKey+"');\" >删除</a>" +
                    "<a class='accessory_downloadBtn' href='javascrip:void(0);' onclick=\"accessoryDownloadAccessory('" + accessoryId + "');\" >下载</a>"+
                    "</td>" +
                    "</tr>"*/
                    "<li id=\""+accessoryId+"_tr\">" +
                    "<input id='"+accessoryId+"' type='hidden' name='add_accessoryIds' value='"+accessoryId+"'/>"+
                    "<p onclick=\"accessoryDownloadAccessory('" + accessoryId + "');\">"+files[i].name +
                    "<span>("+(files[i].size/1024).toFixed(2)+"KB)</span></p>"+
                    "<a href='javascript:void(0);' onclick=\"accessoryDeleteAccessory('" + accessoryId + "','"+packageKey+"');\" >删除</a>" +
                    "</li>"

                );
            }
        },
        /**
         *进度条
         */
        progressall: function (e, data) {
           /* var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress .bar').css(
                'width',
                progress + '%'
            );
            $('#progress .bar').html(progress+"%");*/
        },
        //失败
        fail:function(e,data){
            alert("上传失败！");
        }
    });
    $("#"+packageKey+"").click();
}

function showProgress(packageKey){
    var width=$("#"+packageKey+"accessory_div").width();
    var height=$("#"+packageKey+"accessory_div").height();
   // $("#"+packageKey+"progressShade").width(width);
    //$("#"+packageKey+"progressShade").height(height);
    $("#"+packageKey+"progressShade").css({
        "opacity":"0.3",
        "background-color":"#DCDCDC",
        "width":width+"px",
        "height":height+"px",
        "text-align":"center",
        "line-height":height+"px"

    });
    $("#"+packageKey+"progressShade").append("<img src='"+rootPath+"/resources/themes/images/loading-2.gif'/>");
    $("#"+packageKey+"progressShade").show();

}
function hideProgress(packageKey){
    $("#"+packageKey+"progressShade").children("img").remove();
    $("#"+packageKey+"progressShade").hide();
}
/**
 * 删除附件的方法
 */
function accessoryDeleteAccessory(accessoryId,packageKey){
    $("#"+accessoryId+"_tr").remove();
    $("#"+packageKey+"accessoryTable").append("<input id='"+accessoryId+"' type='hidden' name='delete_accessoryIds' value='"+accessoryId+"'/>");
}
/**
 * 下载附件的方法
 * @param accessoryId
 */
function accessoryDownloadAccessory(accessoryId){

        //var guid = getGuid();
        //var ids =dangerSourceUtil.pointDataIds.toString();
        var form=$("<form>");//定义一个form表单
        form.attr("style","display:none");
        form.attr("target","");
        form.attr("method","post");
        form.attr("action",rootPath+"/accessory/download.shtml");
        $("body").append(form);//将表单放入web页面中
        //将id放入表单
        var input1=$("<input>");
        input1.attr("type","hidden");
        input1.attr("name","accessoryId");
        input1.attr("value",accessoryId);
        form.append(input1);
        form.submit();//表单提交

}
function verifyFileType(typeArrStr,type){
    var typeArr = typeArrStr.split(',');
    var flag=false;
    for(var i=0;i<typeArr.length;i++){
        if(typeArr[i]==type){
            flag=true;
        }
    }
    return flag;

}
/**
 * 获取当前时间
 * @returns {string}
 */
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + date.getHours() + seperator2 + date.getMinutes()
        + seperator2 + date.getSeconds();
    return currentdate;
}
/**
 * 获取项目根路径
 * @returns {string}
 */
function getRootPath(){
    //获取当前网址，如： http://localhost:8088/test/test.jsp
    var curPath=window.document.location.href;
//获取主机地址之后的目录，如： test/test.jsp
    var pathName=window.document.location.pathname;
    var pos=curPath.indexOf(pathName);
//获取主机地址，如： http://localhost:8088
    var localhostPaht=curPath.substring(0,pos);
//获取带"/"的项目名，如：/test
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    return localhostPaht+projectName
}